import type {
  CreateCrudOptionsProps,
  CreateCrudOptionsRet,
  CrudExpose,
} from '@fast-crud/fast-crud';
import type { Key } from 'ant-design-vue/es/vc-tree/interface';

import type { Ref } from 'vue';

import type { ExtendedModalApi } from '@vben/common-ui';
import type { Undefinedable } from '@vben/types';

import type { BaseEmployeeModel, FormRulesExt } from '#/api';
import type { ActionEnum } from '#/enums/commonEnum';

import { ref } from 'vue';

import { useAccess } from '@vben/access';
import { $t } from '@vben/locales';

import { dict } from '@fast-crud/fast-crud';

import { BaseEmployeeApi } from '#/api/basic/user/baseEmployee';
import { BaseOrgApi } from '#/api/basic/user/baseOrg';
import { BasePositionApi } from '#/api/basic/user/basePosition';
import { ScopeTypeEnum } from '#/enums/base';
import { DictEnum } from '#/enums/commonEnum';
import { PermCode } from '#/enums/perm';
import {
  backendDict,
  createdTimeColumn,
  deleteButton,
  indexColumn,
  STATE_CONSTANT_DICT,
  transformQuery,
} from '#/plugins/fast-crud/common';

const { hasPermission } = useAccess();
const permCode = PermCode.basic.user.baseEmployee;

type ContextRef = {
  bindRoleRef: Ref<Undefinedable<ExtendedModalApi>>;
  invitationUserRef: Ref<Undefinedable<ExtendedModalApi>>;
  orgIdList: Ref<Undefinedable<Key[]>>;
  resetPasswordRef: Ref<Undefinedable<ExtendedModalApi>>;
};
export function createCrudOptions(
  props: CreateCrudOptionsProps<
    BaseEmployeeModel.BaseEmployeeResultVO,
    ContextRef
  >,
): CreateCrudOptionsRet<BaseEmployeeModel.BaseEmployeeResultVO> {
  const selectedRowKeys = ref<string[]>([]);

  return {
    crudOptions: {
      request: {
        pageRequest: BaseEmployeeApi.pageRequest,
        addRequest: BaseEmployeeApi.addRequest,
        editRequest: BaseEmployeeApi.editRequest,
        delRequest: BaseEmployeeApi.delRequest,
        infoRequest: BaseEmployeeApi.infoRequest,
        transformQuery: (query) => {
          const tq = transformQuery(query);
          tq.model.orgIdList = props.context.orgIdList.value;
          return tq;
        },
      },
      actionbar: {
        buttons: {
          add: {
            show: hasPermission(permCode.add),
          },
          invitationUser: {
            show: hasPermission(permCode.invitation),
            text: '邀请用户',
            async click() {
              props.context.invitationUserRef.value?.open();
            },
          },
          ...deleteButton({
            crudExpose: props.crudExpose,
            selectedRowKeys,
            role: permCode.delete,
            removeFn: BaseEmployeeApi.remove,
          }),
        },
      },
      table: {
        striped: true,
        rowKey: 'id',
        rowSelection: {
          type: 'checkbox',
          selectedRowKeys,
          onChange: (changed: string[]) => {
            selectedRowKeys.value = changed;
          },
        },
      },
      rowHandle: {
        width: '200px',
        buttons: {
          view: { show: true },
          edit: { show: hasPermission(permCode.edit) },
          remove: { show: hasPermission(permCode.delete) },
          bind: {
            show: hasPermission(permCode.bindRole),
            order: 0,
            text: '绑定角色',
            type: 'link',
            size: 'small',
            dropdown: true,
            click(context) {
              props.context.bindRoleRef.value?.setData({
                scopeType: ScopeTypeEnum.EMPLOYEE,
                id: context.row.id,
              });
              props.context.bindRoleRef.value?.open();
            },
          },
          copy: {
            show: hasPermission(permCode.add),
            dropdown: true,
            click(context) {
              props.crudExpose.openCopy(context);
            },
          },
          reset: {
            show: hasPermission(permCode.restPwd),
            dropdown: true,
            text: '重置密码',
            click(context) {
              props.context.resetPasswordRef.value?.setData({
                record: context.row,
              });
              props.context.resetPasswordRef.value?.open();
            },
          },
        },
      },
      columns: {
        ...indexColumn(props.crudExpose),
        realName: {
          title: $t('basic.user.baseEmployee.realName'),
          type: 'text',
          search: { show: true },
        },
        positionId: {
          title: $t('basic.user.baseEmployee.positionId'),
          type: 'dict-select',
          dict: dict({
            value: 'id',
            label: 'name',
            async getData() {
              return await BasePositionApi.query({});
            },
          }),
          column: { component: { type: 'text' } },
          search: { show: true },
        },
        orgIdList: {
          title: '所属部门',
          type: 'dict-tree',
          form: {
            component: { multiple: true },
          },
          column: { component: { type: 'text' } },
          dict: dict({
            isTree: true,
            value: 'id',
            label: 'name',
            async getData() {
              return await BaseOrgApi.tree({});
            },
          }),
        },
        positionStatus: {
          title: $t('basic.user.baseEmployee.positionStatus'),
          type: 'dict-radio',
          dict: backendDict(DictEnum.POSITION_STATUS),
          search: { show: true },
          addForm: {
            value: '10',
          },
          column: { width: 80 },
        },
        state: {
          title: $t('basic.user.baseEmployee.state'),
          type: 'dict-radio',
          dict: STATE_CONSTANT_DICT,
          search: { show: true },
          addForm: {
            value: true,
          },
          form: {
            component: {
              optionName: 'a-radio-button',
            },
          },
          column: { width: 80 },
        },
        username: {
          title: $t('devOperation.tenant.defUser.username'),
          type: 'text',
          editForm: { show: false },
          column: { show: false },
        },
        mobile: {
          title: $t('devOperation.tenant.defUser.mobile'),
          type: 'text',
          editForm: { show: false },
          column: { show: false },
        },
        email: {
          title: $t('devOperation.tenant.defUser.email'),
          type: 'text',
          form: { show: false },
          viewForm: { show: true },
          column: { show: false },
        },
        idCard: {
          title: $t('devOperation.tenant.defUser.idCard'),
          type: 'text',
          form: { show: false },
          viewForm: { show: true },
          column: { show: false },
        },
        wxOpenId: {
          title: $t('devOperation.tenant.defUser.wxOpenId'),
          type: 'text',
          form: { show: false },
          viewForm: { show: true },
          column: { show: false },
        },
        ddOpenId: {
          title: $t('devOperation.tenant.defUser.ddOpenId'),
          type: 'text',
          form: { show: false },
          viewForm: { show: true },
          column: { show: false },
        },
        nickName: {
          title: $t('devOperation.tenant.defUser.nickName'),
          type: 'text',
          form: { show: false },
          viewForm: { show: true },
          column: { show: false },
        },
        sex: {
          title: '性别',
          type: 'dict-select',
          dict: backendDict(DictEnum.Sex),
          addForm: { value: '1' },
          editForm: { show: false },
          column: { show: false },
        },
        nation: {
          title: '民族',
          type: 'dict-select',
          dict: backendDict(DictEnum.NATION),
          editForm: { show: false },
          column: { show: false },
        },
        education: {
          title: '学历',
          type: 'dict-select',
          dict: backendDict(DictEnum.EDUCATION),
          editForm: { show: false },
          column: { show: false },
        },
        workDescribe: {
          title: $t('devOperation.tenant.defUser.workDescribe'),
          type: 'textarea',
          form: { show: false, col: { span: 24 } },
          viewForm: { show: true },
          column: { show: false },
        },
        passwordErrorLastTime: {
          title: $t('devOperation.tenant.defUser.passwordErrorLastTime'),
          type: 'text',
          form: { show: false },
          viewForm: { show: true },
          column: { show: false },
        },
        passwordErrorNum: {
          title: $t('devOperation.tenant.defUser.passwordErrorNum'),
          type: 'text',
          form: { show: false },
          viewForm: { show: true },
          column: { show: false },
        },
        passwordExpireTime: {
          title: $t('devOperation.tenant.defUser.passwordExpireTime'),
          type: 'text',
          form: { show: false },
          viewForm: { show: true },
          column: { show: false },
        },
        lastLoginTime: {
          title: $t('devOperation.tenant.defUser.lastLoginTime'),
          type: 'text',
          form: { show: false },
          viewForm: { show: true },
          column: { show: false },
        },
        ...createdTimeColumn({}),
      },
      form: {
        wrapper: {
          is: 'a-drawer',
          width: '50%',
          draggable: false,
        },
        group: {
          type: 'tabs', // tab
          accordion: false, // 手风琴模式
          displayDirective: 'show',
          triggerAreas: ['arrow'],
          groups: {
            employee: {
              header: '员工信息',
              columns: [
                'realName',
                'state',
                'orgIdList',
                'positionId',
                'positionStatus',
              ],
            },
            userInfo: {
              header: '用户信息',
              columns: [
                'username',
                'mobile',
                'email',
                'idCard',
                'wxOpenId',
                'ddOpenId',
                'nickName',
                'sex',
                'nation',
                'education',
                'workDescribe',
              ],
            },
            other: {
              header: '其他',
              columns: [
                'passwordErrorLastTime',
                'passwordErrorNum',
                'passwordExpireTime',
                'lastLoginTime',
                'createdTime',
              ],
            },
          },
        },
      },
    },
  };
}

export const frontRules = (
  _crudExpose: CrudExpose,
  _mode: ActionEnum,
): FormRulesExt => {
  return {};
};
